package org.infodavid.common.impl.services.validators;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.persistence.PersistenceException;

import org.infodavid.common.model.IApplicationSettings;
import org.infodavid.common.services.IApplicationContext;
import org.infodavid.common.services.exception.DuplicatedEntityException;
import org.infodavid.common.services.exceptions.ServiceException;

/**
 * The Class DefaultApplicationSettingsValidator.
 */
public class DefaultApplicationSettingsValidator extends AbstractValidator<IApplicationSettings> {

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.services.validators.IValidator#validate(org.infodavid.common.services.
	 * IApplicationContext, java.io.Serializable)
	 */
	public void validate(final IApplicationContext context, final IApplicationSettings value)
	    throws ServiceException {
		super.validate(context, value);
	}

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.services.validators.IValidator#validate(org.infodavid.common.services.
	 * IApplicationContext, java.util.Collection)
	 */
	public void validate(final IApplicationContext context,
	    final Collection<IApplicationSettings> items) throws ServiceException, PersistenceException {
		final Set<String> stringSet = new HashSet<String>();

		if (items == null || items.size() == 0) {}
		else {
			final Iterator<IApplicationSettings> ite = items.iterator();
			IApplicationSettings item;

			while (ite.hasNext()) {
				item = ite.next();

				if (item == null) {
					throw new IllegalArgumentException(IApplicationSettings.APPLICATION_SETTINGS);
				}
				else if (item.getProduct() == null) {
					validate(context, item);
				}
				else if (stringSet.contains(item.getProduct())) {
					throw new DuplicatedEntityException(IApplicationSettings.class, item.getProduct());
				}
				else {
					validate(context, item);
					stringSet.add(item.getProduct());
				}
			}
		}
	}
}
